package com.zhz.lib.cms.manage.type;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.zhz.lib.cms.domain.type.Sortmap;
import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.hibernate.BaseDAO;
import com.zhz.project.common.util.zhzutil.ZhzHttpRequestUtil;

public class TypeManageAction extends DispatchAction {
    private BaseDAO baseDao;

    /**
     * 不给参数，默认执行此处
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */
    @Override
    public ActionForward unspecified(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response)
                                                                                              throws Exception {
        return typemanage(mapping, form, request, response);
    }

    /**
     * 类型管理
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward typemanage(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("sortid", ZhzHttpRequestUtil.getParameters(request, "sortid"));
        return mapping.findForward("type-manage");
    }

    /**
     * 显示类型列表
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    public ActionForward typelist(ActionMapping mapping, ActionForm form,
                                  HttpServletRequest request, HttpServletResponse response) {

        String sortid = ZhzHttpRequestUtil.getParameters(request, "sortid");
        if (StringUtil.equals(sortid, "0")) {
            request.setAttribute("fatherValue", "CMS类型根目录");
            request.setAttribute("sortid", 0);
        } else {
            Sortmap smp = (Sortmap) baseDao.findOneObject("Sortmap", "sortMapID", sortid);
            if (smp != null) {
                request.setAttribute("fatherValue", smp.getValue());
                request.setAttribute("sortid", sortid);
            }
        }

        // 根据sortMapId 排列
        List sortlist = baseDao.findbyorderlimit("Sortmap", "fatherId", sortid,
            "order by sortMapId ASC");

        request.setAttribute("sortlist", sortlist);
        return mapping.findForward("type-list");
    }

    /**
     * 显示树形目录
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    public ActionForward typetree(ActionMapping mapping, ActionForm form,
                                  HttpServletRequest request, HttpServletResponse response) {
        ArrayList<TreeMap> sortEntryArrayTreemap = new ArrayList<TreeMap>();

        int sortid = Integer.parseInt(request.getParameter("sortid"));

        // 递归，找到所有属性目录的节点
        findChildNode(sortid, sortEntryArrayTreemap, 0);

        String javascriptline = " ";

        for (int i = sortEntryArrayTreemap.size() - 1; i >= 0; i--) {
            TreeMap sortEntry = sortEntryArrayTreemap.get(i);

            String fatherid = sortEntry.get("fatherid").toString();
            String sortid2 = sortEntry.get("sortid").toString();
            String sortEntryDesc = sortEntry.get("sortEntryDesc").toString();
            String TREEDEEP = sortEntry.get("TREEDEEP").toString();
            String ifhavechild = sortEntry.get("ifhavechild").toString();

            // m_parent: 插入点，父节点ID
            // m_id: 节点ID
            // m_name: 节点名称
            // m_link: 节点链接
            // m_level: 节点的层次
            // m_isFile: 是否文件，用来决定节点的图标
            // m_fileICO: 如果是文件，可以添加一个图标链接；如果值为空，使用默认值
            // m_rdo: 添加一个单选框
            // m_chk: 添加一个复选框

            javascriptline = "   add_item('" + fatherid + "','" + sortid2 + "','" + sortEntryDesc
                             + "','/libCMS/typeManage.do?method=typelist&sortid=" + sortid2 + "','"
                             + TREEDEEP + "'," + ifhavechild + ",'','');\n" + javascriptline;

        }

        request.setAttribute("javascriptline", javascriptline);
        return mapping.findForward("type-tree");

    }

    /**
     * 递归算法 遍历子节点
     * 
     * @param fatherid
     * @param sortEntryArrayTreemap
     * @param level
     *            当前调用的深度，可以表示当前节点的深度
     * @throws RuntimeException
     */
    @SuppressWarnings("unchecked")
    public void findChildNode(int fatherid, ArrayList<TreeMap> sortEntryArrayTreemap, int level)
                                                                                                throws RuntimeException {

        List sortlist = baseDao.findbyorderlimit("Sortmap", "fatherId", Integer.toString(fatherid),
            "");
        if (sortlist == null)
            return;
        else if (sortlist.size() == 0) {
            return;
        } else {
            for (Iterator it = sortlist.iterator(); it.hasNext();) {
                // 获取该节点
                Sortmap smp = (Sortmap) it.next();
                // 获取该节点的id
                int showchildid = smp.getSortMapId();

                // 查询该节点的所有子节点/////
                List sortlist2 = baseDao.find("Sortmap", "fatherId", Integer.toString(showchildid));

                boolean ifhavechild = false;
                if (sortlist2 != null && sortlist2.size() > 1) {
                    // 如果有子节点，则标注一下
                    ifhavechild = true;
                }

                // m_parent: 插入点，父节点ID
                // m_id: 节点ID
                // m_name: 节点名称
                // m_link: 节点链接
                // m_level: 节点的层次

                TreeMap sortEntryTreemap = new TreeMap();
                sortEntryTreemap.put("sortid", showchildid);
                // 父节点的id
                sortEntryTreemap.put("fatherid", smp.getFatherId());
                // 该节点的描述
                sortEntryTreemap.put("sortEntryDesc", smp.getDescription());

                sortEntryTreemap.put("ifhavechild", ifhavechild);

                // 将文件夹缩进后，将文件夹下所有的file的位置缩进
                sortEntryTreemap.put("TREEDEEP", level + 1);
                sortEntryArrayTreemap.add(sortEntryTreemap);
                this.findChildNode(showchildid, sortEntryArrayTreemap, level + 1);

            }
        }
    }

    /**
     * 类型的添加和删除
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    public ActionForward typeadddel(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response) {
        String sortidstr = ZhzHttpRequestUtil.getParameters(request, "sortid");
        request.setAttribute("sortid", sortidstr);

        String currentOperation = null;
        Enumeration parameterNames = request.getParameterNames();

        while (parameterNames.hasMoreElements()) {
            String name = (String) parameterNames.nextElement();
            // 根据提交的按钮，执行不同的代码段
            if (StringUtil.equals(name, "Delete") || StringUtil.equals(name, "Add")) {
                currentOperation = name;
            }
        }

        // 如果执行 添加命令
        if (StringUtil.equals(currentOperation, "Add")) {
            if (StringUtil.isNotBlank(sortidstr)) {
                int sortid = Integer.parseInt(sortidstr);

                if (sortid == 0) {
                    request.setAttribute("result", "不允许添加一级类目");
                    return mapping.findForward("type-result");
                }
                String type = ZhzHttpRequestUtil.getParameters(request, "type");
                String description = ZhzHttpRequestUtil.getParameters(request, "description");
                String value = ZhzHttpRequestUtil.getParameters(request, "value");

                Sortmap smp = new Sortmap();

                smp.setDescription(description);
                smp.setFatherId(sortid);
                smp.setValue(value);
                smp.setType(type);

                if (baseDao.save(smp)) {
                    request.setAttribute("result", "添加成功");
                }
            }
        }

        // 如果执行 Delete 添加命令
        if (StringUtil.equals(currentOperation, "Delete")) {

            String deletesortidStr = ZhzHttpRequestUtil.getParameters(request, "deletesortid");
            if (StringUtil.isNotBlank(deletesortidStr)) {
                int deletesortid = Integer.parseInt(deletesortidStr);
                Sortmap sortmap = (Sortmap) baseDao.findOneObject("Sortmap", "sortMapId",
                    deletesortid + "");
                if (sortmap != null && sortmap.getFatherId() == 0) {
                    request.setAttribute("result", "一级类目不允许删除");
                    return mapping.findForward("type-result");
                }
                boolean delete = baseDao.execute("delete from Sortmap where sortMapId="
                                                 + deletesortid);
                if (delete) {
                    request.setAttribute("result", "删除成功");
                }
            }

        }
        return mapping.findForward("type-result");
    }

    public void setBaseDao(BaseDAO baseDao) {
        this.baseDao = baseDao;
    }

}